<template>
    <el-container>
        <el-main class="form">
            <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm" label-position="right">
                <el-row :gutter="1">
                    <el-col :span="12">
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="检验单号" prop="purchase_test_id">
                                    <template #label>
                                        <div @click="test_show">
                                            检验单号
                                        </div>
                                    </template>
                                    <sc-auto-complete  v-model="purchase_test_code" :api="$API.business.inspect.order.list" :params-key="'test_code'" :rows-key="'rows'" :value-key="'test_code'" :additionalParams="{work_uid: search.work_uids[0]}" placeholder="检验单号" @select="getHouse"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="日期" prop="action_date">
                                    <el-date-picker v-model="form.action_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="操作" prop="action_type">
                                    <el-select v-model="form.action_type" placeholder="请输入" filterable clearable>
                                        <el-option label="最终检验" :value="1"></el-option>
                                        <el-option label="跑米" :value="2"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="入库单号" prop="purchase_ware_id">
                                    <template #label>
                                        <div @click="test_show_check">
                                            入库单号
                                        </div>
                                    </template>
                                    <el-input v-model="purchase_ware_code" readonly placeholder="入库单号"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="计重" prop="weight">
                                    <el-input v-model="form.weight" clearable placeholder="" @input="weightInput" type="number" @mousewheel.prevent @focus="common.inputFocus($event)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="检验机台" prop="machine_id">
                                    <el-input v-model="machine_name" readonly @click="checkMachine" placeholder="请选择"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="16"> 
                                <el-row :gutter="1">
                                    <el-col :span="12">
                                        <el-form-item label="品名" prop="goods_name">
                                            <el-input v-model="form.goods_name" readonly></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计数" prop="number">
                                            <el-input v-model="form.number" clearable @input="numberInput" type="number" @mousewheel.prevent @focus="common.inputFocus($event)"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="1">
                                    <el-col :span="12">
                                        <el-form-item label="货号" prop="goods_code">
                                            <el-input v-model="form.goods_code" readonly></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="检验数量" prop="check_num">
                                            <el-input v-model="form.check_num" clearable readonly></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="检验员" prop="work_uids">
                                    <template #label>
                                        <div>
                                            <div>检验员</div>
                                            <el-button type="primary" text size="small" @click="select_user">选择</el-button>
                                        </div>
                                    </template>
                                    <div class="border">
                                        <div v-for="(item,index) in userList" :key="index" style="line-height: 20px;">
                                            <el-tag  closable type="info" style="margin-right: 2px" @close="delTag(index)">
                                                {{ item.name }}
                                            </el-tag>
                                            <el-tag type="info" @click="table_edit(item)">装卸货</el-tag>
                                        </div>
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="折码" prop="folding_id">
                                    <el-select v-model="form.folding_id" placeholder="请选择" filterable clearable @change="foldChange">
                                        <el-option v-for="item in foldingList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="拼拆选项" prop="type" class="elType">
                                    <el-radio-group v-model="form.type" @change="typeChange">
                                        <el-radio-button  :label="1" size="default">正常</el-radio-button>
                                        <el-radio-button  :label="2" size="default">合成</el-radio-button>
                                        <el-radio-button  :label="3" size="default">1分2</el-radio-button>
                                        <el-radio-button  :label="4" size="default">1分3</el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="number" label-width="0" class="elType">
                                    <el-checkbox v-model="form.com1_status" size="large" label="连接COM1" @change="changeAll('com1_status',$event)"  />
                                    <el-checkbox v-model="form.com2_status" size="large" label="连接COM2" @change="changeAll('com2_status',$event)"  />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="颜色" prop="color">
                                    <el-select v-model="form.color" placeholder="请选择" filterable clearable @change="colorChange">
                                        <el-option v-for="(item,index) in samplecolorList" :key="index" :label="item.name" :value="item.name"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="消耗数量" prop="use_num">
                                    <el-input v-model="form.use_num" clearable :readonly="form.type != 2"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="次品种类" prop="reject_cate_id">
                                    <el-select v-model="form.reject_cate_id" placeholder="请选择" filterable clearable>
                                        <el-option v-for="item in rejectList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="Color" prop="color_id">
                                    <el-select v-model="form.color_id" placeholder="请选择" filterable clearable>
                                        <el-option v-for="item in colorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="净重" prop="net_weight">
                                    <el-input v-model="form.net_weight" readonly></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="打印份数">
                                    <el-input v-model="form.reject_num" placeholder="" clearable type="number" @mousewheel.prevent>
                                        <template #append>份</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="花型" prop="flower">
                                    <el-select v-model="form.flower" placeholder="请选择" filterable clearable @change="flowerChange">
                                        <el-option v-for="(item,index) in flowerList" :key="index" :label="item.flower" :value="item.flower"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="米数" prop="meter">
                                    <el-input v-model="form.meter" readonly></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="标签选择">
                                    <el-select v-model="form.reject_type" placeholder="" filterable clearable>
                                        <el-option label="码数" :value="1"></el-option>
                                        <el-option label="米数" :value="2"></el-option>
                                        <el-option label="重量+米数" :value="3"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="来数" prop="come">
                                    <!-- <el-input v-model="form.come" clearable type="number" @mousewheel.prevent @keyup.enter="comeEnter" @input="comeInputChange" @focus="common.inputFocus($event)"></el-input> -->
                                    <el-input-number v-model="form.come" :min="0" :controls="false" ref="comeInput" @keyup.enter="comeEnter" @input="comeInputChange" @focus="common.inputFocus($event)" :value-on-clear="0" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="码数" prop="code_number">
                                    <el-input v-model="form.code_number" readonly></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="上限 ">
                                    <div style="display: flex;justify-content: space-between;width: 100%;">
                                        <el-input-number v-model="up_limit" :min="0" :controls="false" @focus="common.inputFocus($event)" style="width: 60px" />
                                        <div style="font-weight: bold">下限 <el-input-number v-model="down_limit" :min="0" :controls="false" @focus="common.inputFocus($event)" style="width: 60px" /></div>
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="8">
                                <el-form-item label="剪数" prop="cut">
                                    <!-- <el-input v-model="form.cut" clearable type="number" @mousewheel.prevent @input="cutInputChange" @keyup.enter="is_dialog" @focus="common.inputFocus($event)"></el-input> -->
                                    <el-input-number v-model="form.cut" :min="0" :controls="false" ref="cutInput" @input="cutInputChange" @keyup.enter="is_dialog" @focus="common.inputFocus($event)" :value-on-clear="0" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="克重" prop="gram_weight">
                                    <el-input v-model="form.gram_weight" readonly>
                                        <template #append>克</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="克重差 ">
                                    <div style="display: flex;justify-content: space-between;width: 100%;">
                                        <el-input-number v-model="weight_cha" :min="0" :controls="false" @focus="common.inputFocus($event)" style="width: 60px" />
                                        <div style="font-weight: bold">来码差 <el-input-number v-model="come_cha" :min="0" :controls="false" @focus="common.inputFocus($event)" style="width: 60px" /></div>
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="12">
                        <el-row :gutter="1">
                            <el-col :span="12">
                                <el-form-item  prop="flower_image">
                                    <sc-upload v-model="form.flower_image" disabled height="400" width="300"></sc-upload>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </el-form>
            <el-header>
                <div class="right-panel">
                    <div class="right-panel-search">
                        <el-input v-model="search.purchase_ware_code" placeholder="入库单号" clearable @keyup.enter="upsearch"></el-input>
                        <el-input v-model="search.roll_code" placeholder="品名|条码" clearable @keyup.enter="upsearch"></el-input>
                        <el-date-picker v-model="search.date" :value-format="'YYYY-MM-DD'" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        <el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
                    </div>
                </div>
            </el-header>
            <el-main class="nopadding">
                <scTable ref="table" :apiObj="apiObj" row-key="id" @selection-change="selectionChange" border tableName="testTable" :column="testColumn" :params="{action_test: 1, work_uid: userList[0].id, date: this.search.date}" height="calc(100vh - 500px)">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <template #reject_type="{row}">
                        {{row.reject_type == 1 ? '码数' : row.reject_type == 2 ? '米数' : '重量+米数'}}
                    </template>
                    <template #action_type="{row}">
                        {{row.action_type == 1 ? '最终检验' : '跑米'}}
                    </template>
                    <template #operation="scope">
                        <div class="buttonFlex">
                            <el-button icon="el-icon-printer" type="primary" size="small" @click="table_print(scope.row, scope.$index)" v-auth="'execute.print'"></el-button>
                            <el-button icon="el-icon-edit" type="primary" color="#34a853" size="small" @click="table_edit(scope.row, scope.$index)" v-auth="'execute.edit'"></el-button>
                            <el-popconfirm title="确定删除吗?" @confirm="table_del(scope.row, scope.$index)">
                                <template #reference>
                                    <el-button icon="el-icon-delete" type="danger" size="small" v-auth="'execute.delete'"></el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </template>
                    <!-- <el-table-column label="类型" prop="reject_type" width="120" align="center">
                        <template #default="{row}">
                            {{row.reject_type == 1 ? '码数' : row.reject_type == 2 ? '米数' : '重量+米数'}}
                        </template>
                    </el-table-column>
                    <el-table-column label="消耗" prop="use_num" width="100" align="center"></el-table-column>
                    <el-table-column label="布卷条码" prop="roll_code" width="130" align="center"></el-table-column>
                    <el-table-column label="日期" prop="action_date" width="120" align="center"></el-table-column>
                    <el-table-column label="入库单号" prop="purchaseware.purchase_ware_code" width="150" align="center"></el-table-column>
                    <el-table-column label="检验单号" prop="test.test_code" width="150" align="center"></el-table-column>
                    <el-table-column label="货号" prop="goods_code" width="120" align="center"></el-table-column>
                    <el-table-column label="品名" prop="goods_name" width="120" align="center"></el-table-column>
                    <el-table-column label="来数" prop="come" width="100" align="center"></el-table-column>
                    <el-table-column label="净重" prop="net_weight" width="100" align="center"></el-table-column>
                    <el-table-column label="米数" prop="meter" width="100" align="center"></el-table-column>
                    <el-table-column label="码数" prop="code_number" width="100" align="center"></el-table-column>
                    <el-table-column label="剪数" prop="cut" width="100" align="center"></el-table-column>
                    <el-table-column label="折码" prop="folding" width="100" align="center"></el-table-column>
                    <el-table-column label="克重" prop="gram_weight" width="100" align="center"></el-table-column>
                    <el-table-column label="计重" prop="weight" width="100" align="center"></el-table-column>
                    <el-table-column label="计数" prop="number" width="100" align="center"></el-table-column>
                    <el-table-column label="颜色" prop="color" width="120" align="center"></el-table-column>
                    <el-table-column label="Color" prop="color_en" width="120" align="center"></el-table-column>
                    <el-table-column label="花型" prop="flower" width="120" align="center"></el-table-column>
                    <el-table-column label="次品种类" prop="reject_cate" width="120" align="center"></el-table-column>
                    <el-table-column label="机台" prop="machine.name" width="120" align="center"></el-table-column>
                    <el-table-column label="检验员" prop="work_uids_name" width="120" align="center"></el-table-column>
                    <el-table-column label="操作" prop="action_type" width="120" align="center">
                        <template #default="{row}">
                            {{row.action_type == 1 ? '最终检验' : '跑米'}}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" align="center" width="150">
						<template #default="scope">
							<div class="buttonFlex">
								<el-button text icon="el-icon-printer" type="primary" size="small" @click="table_print(scope.row, scope.$index)" v-auth="'execute.print'"></el-button>
								<el-button text icon="el-icon-edit" color="#34a853" size="small" @click="table_edit(scope.row, scope.$index)" v-auth="'execute.edit'"></el-button>
								<el-popconfirm title="确定删除吗?" @confirm="table_del(scope.row, scope.$index)">
									<template #reference>
										<el-button text icon="el-icon-delete" type="danger" size="small" v-auth="'execute.delete'"></el-button>
									</template>
								</el-popconfirm>
							</div>
						</template>
					</el-table-column> -->
                </scTable>
            </el-main>
        </el-main>
    </el-container>
    <select-machine v-if="dialog.machine" ref="machineDialog" @success="machineBack" @closed="dialog.machine = false"></select-machine><!-- 机台 -->
    <select-admin v-if="dialog.admin" ref="adminDialog" @success="userBack" @closed="dialog.admin = false"></select-admin><!-- 人员 -->
    <el-dialog ></el-dialog>
    <el-dialog :title="dialogTitle" v-model="dialog.dialog" align-center :width="500">
        <template #footer>
			<el-button @click="dialog.dialog = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="end_submit()">保 存</el-button>
		</template>
    </el-dialog>

    <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false"></save-dialog>
    <hi-print ref="printDialog"></hi-print>

    <test-situa v-if="dialog.situa" ref="situaDialog" @success="printBack" @closed="dialog.situa = false"></test-situa>
    <test-print v-if="dialog.print" ref="printDialog" @success="printBack" @closed="dialog.print = false"></test-print>
</template>

<script>
import selectMachine from '@/views/basic/machine/selectMachine.vue'
import selectAdmin from '@/views/setting/admin/selectAdmin.vue';
import saveDialog from './save'
import HiPrint from '../../hiPrint.vue';
import TestSitua from './testSitua.vue';
import TestPrint from '../order/testPrint.vue';
import config from '@/config'
export default {
    components: { selectMachine, selectAdmin, saveDialog, HiPrint, TestSitua, TestPrint },
    name: '检验',
    data() {
        return {
            dialog: {
                save: false,
                machine: false,
				admin: false,
				dialog: false,
				situa: false,
            },
            isSaveing: false,
            apiObj: null,
            form: {
                purchase_test_id: "",
                action_date: this.moment().format('YYYY-MM-DD'),
                purchase_ware_id: "",
                ware_detail_id: "",
                goods_code: "",
                goods_name: "",
                goods_id: "",
                folding_id: "",
                batch_num: "",
                color_id: "",
                color: "",
                flower: "",
                flower_image: "",
                code_number: "",
                gram_weight: "",
                warehouseids: "",
                check_num: "",
                type: 1,
                net_weight: "",
                meter: "",
                use_num: 1,
                come: 0,
                cut: 0,
                weight: "",
                number: "",
                remark: "",
                action_type: 1,
                work_uids: "",
                machine_id: "",
                reject_cate_id: "",
                reject_num: 2,
                reject_type: 1,
                com1_status: "",
                com2_status: "",
                weight_cha: "",
                come_cha: "",
            },
            com1_status: false,
            com2_status: false,
            ports: [],
            port:{},
            connected:null,
            reader:null,
            message:null,
            serialOptions:{
                baudRate: 9600,
                flowControl: 'none',
                dataBits: 8
            },
            // machineList: [],
            foldingList: [],
            colorList: [],
            rejectList: [],
            samplecolorList: [],
            flowerList: [],
            purchase_test_code: "",
            houseList: [],
            machine_name: "",
            userList: [
                {name: this.$TOOL.data.get("USER_INFO").name,id: this.$TOOL.data.get("USER_INFO").admin_id}
            ],
            start: 0,
            folding_num: 0,
            weight_port: {},
            weight_reader: null,
            weight_start: false,
            meter_port: {},
            meter_reader: null,
            meter_write: null,
            meter_start: false,
            meterInterval:  null,
            rules: {
                purchase_test_id: [ {required: true, message: '请检验单'} ],
                action_date: [ {required: true, message: '请选择日期'} ],
                purchase_ware_id: [ {required: true, message: '请选择入库单'} ],
                machine_id: [ {required: true, message: '请选择检验机台'} ],
                work_uids: [ {required: true, message: '请选择检验员'} ],
            },
            search: {
                purchase_ware_code: null,
                roll_code: null,
                action_date: null,
                work_uids: [this.$TOOL.data.get("USER_INFO").admin_id],
                date: [this.moment().format('YYYY-MM-DD'),this.moment().format('YYYY-MM-DD')],
            },
            up_limit: "",
            down_limit: "",
            weight_cha: "",
            come_cha: "",
            house_weight: "",
            is_refresh: true,
            dialogTitle: "",
            read_number: "",
            apply_name: "",
            dye_factory_name: "",
            process_factory_name: "",
            purchase_ware_code: "",
            testColumn: [
                { label: "类型", prop: "reject_type",},
                { label: "消耗", prop: "use_num",},
                { label: "布卷条码", prop: "roll_code",},
                { label: "日期", prop: "action_date",},
                { label: "入库单号", prop: "purchaseware.purchase_ware_code",},
                { label: "检验单号", prop: "test.test_code",},
                { label: "货号", prop: "goods_code",},
                { label: "品名", prop: "goods_name",},
                { label: "来数", prop: "come",},
                { label: "净重", prop: "net_weight",},
                { label: "米数", prop: "meter",},
                { label: "码数", prop: "code_number",},
                { label: "剪数", prop: "cut",},
                { label: "折码", prop: "folding",},
                { label: "克重", prop: "gram_weight",},
                { label: "计重", prop: "weight",},
                { label: "计数", prop: "number",},
                { label: "颜色", prop: "color",},
                { label: "Color", prop: "color_en",},
                { label: "花型", prop: "flower",},
                { label: "次品种类", prop: "reject_cate",},
                { label: "机台", prop: "machine.name",},
                { label: "检验员", prop: "work_uids_name",},
                { label: "操作", prop: "action_type",},
                { label: "操作", prop: "operation", width: "230",fixed: 'right'},
            ],
        }
    },
    unmounted(){
        if (this.meterInterval) {
			clearInterval(this.meterInterval);
			this.meterInterval = null;
		}
        if(this.meter_port && this.meter_start){
            this.meter_port.close()
            this.meter_reader.cancel()
            this.meter_write.close();
            this.meter_port = {}
        }
        if(this.weight_port && this.weight_start){
            this.weight_port.close()
            this.weight_reader.cancel()
            this.weight_port = {}
        }
        if(this.form.machine_id){
            this.$API.business.inspect.start_end_machine.post({id: this.form.machine_id, status: 2})
        }
    },
    mounted() {
        // this.getMachine()
        this.getFolding()
        this.getColor()
        this.getReject()
        // setInterval(async ()=> {
        //     this.form.number ++
        //     this.numberInput(this.form.number)
        // },500)
        setTimeout(()=>{
            this.upsearch()
        },500)
    },
    methods: {
        upsearch(){
            this.search.work_uids = this.userList.map(item=>item.id)
            // this.search.search_field = "roll_code"
            // this.search.search_keyword = this.search.roll_code
            this.apiObj = this.$API.business.inspect.execute.list
            this.$refs.table.upData(this.search)
        },
        async getMachine(){
            var res = await this.$API.basic.machine.all.get()
            this.machineList = res.data
        },
        async getFolding(){
            var res = await this.$API.basic.folding.all.get()
            this.foldingList = res.data
            res.data.map(item => {
                if (item.is_default == 1) {
                    this.form.folding_id = item.id
                    this.up_limit = item.up_limit
                    this.down_limit = item.down_limit
                    this.weight_cha = item.weight_cha
                    this.come_cha = item.come_cha
                    this.foldChange(item.id)
                }
            })
        },
        async getColor(){
            var res = await this.$API.basic.color.all.get()
            let array = []
            res.data.map(item=>{
                array.push({
                    id: item.id,
                    name: `【${item.color_code}】 ${item.name}`,
                    zh_name: item.zh_name
                })
            })
            this.colorList = array
        },
        async getReject(){
            var res = await this.$API.basic.reject.all.get()
            this.rejectList = res.data
        },
        // 输入单号,获取入库单
        async getHouse(data) {
            this.houseList = []
            this.form.test_code = ""
            this.testChange()
            this.form.purchase_test_id = data.id
            this.houseList = data.purchase_ware_code
            this.apply_name = data.apply?.apply_name
            this.dye_factory_name = data.dye_factory_name
            this.process_factory_name = data.process_factory_name
            this.form.goods_name = data.goods_name
        },
        // 入库选择
        async testChange(e){
            this.form.goods_code = ""
            this.form.goods_name = ""
            this.form.goods_id = ""
            this.form.color_id = ""
            this.form.color = ""
            this.form.flower = ""
            this.samplecolorList = []
            this.flowerList = []
            if(!e) return
            var res = await this.$API.business.machining.house.detail.get({id: e});
            console.log(res);
            this.form.goods_code = res.data.goodsName?.code
            this.form.goods_name = res.data.goods_name
            this.form.goods_id = res.data.goods_id
            let sample = []
            let color = res.data.select_colors.split(',')
            color.map(item=>{
                sample.push({
                    name: item
                })
            })
            this.samplecolorList = sample
            this.flowerList = res.data.select_flower_param
        },
        flowerChange(e){
            this.form.flower_image = this.flowerList.find(item=>item.flower == e).flower_image
        },
        // 选择机台
        checkMachine(){
            if(this.start == 1) return this.$message.error('已经开始检验,请勿重新选择')
            this.dialog.machine = true
            this.$nextTick(() => {
                this.$refs.machineDialog.open('add')
            })
        },
        machineBack(data){
            this.machine_name = data.name,
            this.form.machine_id = data.id
        },
        // 选择人员
        select_user(){
            this.dialog.admin = true
            this.$nextTick(() => {
                this.$refs.adminDialog.open()
            })
        },
        userBack(data){
            if(data.length > 3) return this.$message.error('最多选择3个检验员')
            let array = []
            data.map(item=>{
                let exist = this.common.isExist(item.id, this.userList, 'id')
                if (exist) {
                    return
                }
                array.push({
                    id: item.id,
                    name: item.name,
                })
            })
			this.userList = [...this.userList, ...array]
            if(this.userList.length > 3) {
                this.userList.splice(3, this.userList.length)
                this.$message.error('最多选择3个检验员')
            }
        },
        delTag(index){
            this.userList.splice(index, 1)
        },
        colorChange(e){
            let color = e.split('#')[1]
            this.form.color_id = this.colorList.find(item => item.zh_name == color).id
        },
        typeChange(e){
            if(e == 2){
                this.form.use_num = e
            }else if(e == 3 || e == 4){
                this.form.use_num = 0
            }else {
                this.form.use_num = 1
            }
        },
        // 开始/结束检验
        async check(e) {
            if(!this.form.machine_id) return this.$message.error('请选择检验机台')
            if(this.userList.length == 0) return this.$message.error('请选择检验员')
            this.start = e
            await this.$API.business.inspect.start_end_machine.post({id: this.form.machine_id, status: e})
            this.$nextTick(() => {
                this.$refs.comeInput.focus()
            })
        },
        // 来数回车
        comeEnter(){
            this.$nextTick(() => {
                this.$refs.cutInput.focus()
            })
        },
        // 来数输入
        comeInputChange(e){
            if(e != 0){
                this.form.check_num = this.read_number
            }
            // if(e != 0){
            //     if(this.meter_port && this.meter_start){
            //         this.meter_reader.cancel()
            //         this.meter_write.close();
            //     }
            // }else {
            //     this.writeMeterData(this.meter_port)
            // }
        },
        numberInput(e){
            // this.form.meter = e
            if(this.form.come == 0){
                this.form.check_num = e - this.form.cut
                this.read_number = e
            }
            this.cutInputChange(this.form.cut)
            this.total()
        },  
        // 剪数输入
        cutInputChange(e){
            this.form.check_num = Number(this.read_number) - Number(e)
            this.form.meter = this.form.check_num
            this.total()
        },
        total(){
            let code = 0
            if(this.form.meter && this.form.folding_id){
                code = (Number(this.form.meter) / Number(this.folding_num)).toFixed(1)
                this.form.code_number = (Math.ceil(parseFloat(code) * 10 - 0.0000001) / 10).toFixed(1); 
                // this.form.code_number = parseFloat(code).toFixed(1); 
            }
            if(this.form.net_weight && this.form.meter){
                this.form.gram_weight = ((Number(this.form.net_weight) / Number(this.form.meter)) * 1000).toFixed(1)
            }
        },
        // 剪数判断
        is_dialog(){
            if(this.form.cut != 0){
                this.$confirm(`剪数为${this.form.cut},确认开剪?`, '提示', {
                    type: 'warning'
                }).then(() => {
                    this.submit()
                }).catch(() => {})
            }else {
                this.submit()
            }
        },
        // 数据提交
        async submit(){
            let down_limit = Number(this.form.meter) < Number(this.down_limit)
            let up_limit = Number(this.form.meter) > Number(this.up_limit)
            if(this.weight_cha != 0){
                this.form.weight_cha = Number(this.house_weight) - Number(this.form.gram_weight)
            }
            if(this.come_cha != 0){
                this.form.come_cha = Number(this.form.come) - Number(this.form.check_num)
            }
            if(this.form.meter){
                if(down_limit){
                    if(this.form.come_cha > this.come_cha && this.form.weight_cha > this.weight_cha){
                        this.$confirm(`米数小于${this.down_limit}米,当前米数为${this.form.meter}米,且米数可能不准确,克重不足，请确认是否继续提交？`, '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.end_submit()
                        }).catch(() => {})
                    }else if(this.form.come_cha > this.come_cha){
                        this.$confirm(`米数小于${this.down_limit}米,当前米数为${this.form.meter}米,且米数可能不准确，请确认是否继续提交？`, '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.end_submit()
                        }).catch(() => {})
                    }else if(this.form.weight_cha > this.weight_cha){
                        this.$confirm(`米数小于${this.down_limit}米,当前米数为${this.form.meter}米,且克重不足，请确认是否继续提交？`, '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.end_submit()
                        }).catch(() => {})
                    }
                }else if(up_limit){
                    if(this.form.come_cha > this.come_cha && this.form.weight_cha > this.weight_cha){
                        this.$confirm(`米数大于${this.up_limit}米,当前米数为${this.form.meter}米,且米数可能不准确,克重不足，请确认是否继续提交？`, '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.end_submit()
                        }).catch(() => {})
                    }else if(this.form.come_cha > this.come_cha){
                        this.$confirm(`米数大于${this.up_limit}米,当前米数为${this.form.meter}米,且米数可能不准确，请确认是否继续提交？`, '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.end_submit()
                        }).catch(() => {})
                    }else if(this.form.weight_cha > this.weight_cha){
                        this.$confirm(`米数大于${this.up_limit}米,当前米数为${this.form.meter}米,且克重不足，请确认是否继续提交？`, '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.end_submit()
                        }).catch(() => {})
                    }
                }else if(this.form.come_cha > this.come_cha && this.form.weight_cha > this.weight_cha){
                    this.$confirm('米数可能不准确且克重不足,是否继续提交？', '提示', {
                        type: 'warning'
                    }).then(() => {
                        this.end_submit()
                    }).catch(() => {})
                }else if(this.form.come_cha > this.come_cha){
                    this.$confirm('米数可能不准确,是否继续提交？', '提示', {
                        type: 'warning'
                    }).then(() => {
                        this.end_submit()
                    }).catch(() => {})
                }else if(this.form.weight_cha > this.weight_cha){
                    this.$confirm('克重不足,请确认是否继续提交？', '提示', {
                        type: 'warning'
                    }).then(() => {
                        this.end_submit()
                    }).catch(() => {})
                }else {
                    this.end_submit()
                }
            }
        },
        // 最终提交
        async end_submit(){
            this.form.work_uids = this.userList.map(item=>item.id)
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
					this.isSaveing = true;
                    var res = await this.$API.business.inspect.execute.add.post(this.form)
					this.isSaveing = false;
                    if (res.code == 1) {
                        this.$message.success("操作成功")
                        this.is_refresh = false
                        this.resetForm()
                        this.table_print({roll_code: res.data.roll_code})
                        // this.search.roll_code = res.data.roll_code
                        this.upsearch()
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                } else {
					return false;
				}
            })
        },
        resetForm() {
            this.form.come = 0
            this.form.cut = 0
            this.form.check_num = 0
            this.$nextTick(() => {
                this.$refs.comeInput.focus()
            })
            this.$refs.table.refresh()
		},
        foldChange(e){
            let data = this.foldingList.find(item => item.id == e)
            this.folding_num = data.val
            this.up_limit = data.up_limit
            this.down_limit = data.down_limit
            this.total()
        },
        weightInput(e){ 
            this.form.net_weight = e
            this.total()
        },
        async changeAll(name,e){
            this.form[name] = e
            if(e){
                if('serial' in navigator){
                    try{
                        const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
                        if(name == 'com1_status' && this.form.com1_status){
                            this.meter_port = await navigator.serial.requestPort()
                            await this.meter_port.open({ baudRate: 19200, flowControl: 'none', dataBits: 8, stopBits: 1 })
                            this.writeMeterData(this.meter_port)
                            successAudio.play();
                        }
                        if(name == 'com2_status' && this.form.com2_status) {
                            this.weight_port = await navigator.serial.requestPort()
                            await this.weight_port.open({ baudRate: 9600, flowControl: 'none', dataBits: 8 })
                            this.readWeightData(this.weight_port)
                            successAudio.play();
                        }
                    }catch(error){
                        console.log('无可用串口',error);
                        if(name == 'com1_status'){
                            this.form.com1_status = false
                        }
                        if(name == 'com2_status'){
                            this.form.com2_status = false
                        }
                        const errorAudio = new Audio(`${config.API_URL}/audio/error.wav`);
                        errorAudio.play();
                    }
                }
            }else {
                if(name == 'com1_status' && !this.form.com1_status && this.meter_port) {
                    try {
                        // 清除定时器
                        if(this.meterInterval) {
                            clearInterval(this.meterInterval);
                            this.meterInterval = null;
                        }
                        // 取消读取器并释放锁
                        if(this.meter_reader) {
                            this.meter_reader.cancel();
                        }
                        // 取消写入器并释放锁
                        if(this.meter_write) {
                            this.meter_write.close();
                        }
                        // 关闭端口（应该在所有操作完成后最后执行）
                        setTimeout(async () => {
                            await this.meter_port.close();
                            this.meter_start = false;
                        }, 500);
                    } catch(error) {
                        console.log('关闭串口错误', error);
                    }
                }
                if(name == 'com2_status' && !this.form.com2_status && this.weight_port) {
                    try {
                        this.weight_reader.cancel();
                        // 关闭端口（应该在所有操作完成后最后执行）
                        setTimeout(async () => {
                            await this.weight_port.close();
                            this.weight_start = false;
                        }, 500);
                    } catch(error) {
                        console.log('关闭串口错误', error);
                    }
                }
            }
        },
        // 重量数据
        async readWeightData(port){
            this.weight_reader = port.readable.getReader();
            this.weight_start = true;
            let dataBuffer = ''; // 添加数据缓冲区
            const self = this; // 保存this上下文
            try {
                while (this.weight_start){
                    const { value, done } = await this.weight_reader.read();
                    if (done) {
                        this.weight_reader.releaseLock();
                        break;
                    }
                    const writer = new TextDecoder().decode(value);
                    console.log('原始数据:>> ', JSON.stringify(writer));
                    
                    // 将新读取的数据添加到缓冲区
                    dataBuffer += writer;
                    console.log('当前缓冲区:>> ', dataBuffer);
                    
                    // 清理空白字符，保留所有字符
                    dataBuffer = dataBuffer.replace(/\s+/g, '');
                    console.log('清理后缓冲区:>> ', dataBuffer);
                    
                    // 处理逻辑：优先查找完整的标准格式
                    const allContent = dataBuffer;
                    
                    // 1. 完整标准格式：wn00000.00kg
                    const standardFormatMatch = allContent.match(/wn\d+(\.\d+)?kg/);
                    if (standardFormatMatch) {
                        const matchedFormat = standardFormatMatch[0];
                        const weightStr = matchedFormat.replace(/[^0-9.]/g, '');
                        console.log('✓ 检测到标准格式:>> ', matchedFormat);
                        
                        processWeightData(weightStr);
                        
                        // 移除已处理的完整格式
                        dataBuffer = allContent.substring(allContent.indexOf(matchedFormat) + matchedFormat.length);
                        console.log('处理后剩余缓冲区:>> ', dataBuffer);
                        continue;
                    }
                    
                    // 2. 从数据中提取数字部分并构建标准格式
                    // 提取所有数字和小数点
                    const numericPart = allContent.match(/[0-9.]+/g)?.join('') || '';
                    if (numericPart.length > 0 && /\d+/.test(numericPart)) {
                        // 清理数字格式（移除多余小数点）
                        const cleanNumber = numericPart.replace(/\.{2,}/g, '.');
                        if (cleanNumber !== '.') {
                            const weightNum = parseFloat(cleanNumber);
                            if (!isNaN(weightNum) && weightNum >= 0 && weightNum <= 9999.99) {
                                // 构建标准格式 wn00000.00kg
                                const formattedWeight = `wn${weightNum.toString().padStart(7, '0')}kg`;
                                console.log('✓ 构建标准格式:>> ', formattedWeight);
                                
                                processWeightData(cleanNumber);
                                
                                // 更新缓冲区为标准格式（如果还有其他字符）
                                const nonNumericPart = allContent.replace(/[0-9.]+/g, '');
                                dataBuffer = nonNumericPart; // 只保留非数字部分
                                console.log('更新后缓冲区:>> ', dataBuffer);
                                continue;
                            }
                        }
                    }
                    
                    // 3. 处理可能的部分wn前缀或kg后缀
                    if (allContent.includes('wn') || allContent.includes('kg')) {
                        // 提取包含wn和kg的部分
                        // let partialFormat = allContent;
                        
                        // 如果包含kg，尝试提取kg前的数字
                        if (allContent.includes('kg')) {
                            const kgIndex = allContent.indexOf('kg');
                            const beforeKg = allContent.substring(0, kgIndex);
                            const numberMatch = beforeKg.match(/\d+(\.\d+)?$/);
                            
                            if (numberMatch) {
                                const weightStr = numberMatch[0];
                                const weightNum = parseFloat(weightStr);
                                if (!isNaN(weightNum) && weightNum >= 0 && weightNum <= 9999.99) {
                                    // 构建标准格式
                                    const formattedWeight = `wn${weightStr.padStart(7, '0')}kg`;
                                    console.log('✓ 从kg后缀构建标准格式:>> ', formattedWeight);
                                    
                                    processWeightData(weightStr);
                                    
                                    // 移除已处理部分
                                    dataBuffer = allContent.substring(kgIndex + 2);
                                    console.log('处理kg后缀后缓冲区:>> ', dataBuffer);
                                    continue;
                                }
                            }
                        }
                    }
                    
                    // 4. 保留缓冲区中的有效部分（尝试构建标准格式）
                    // 确保缓冲区数据长度合理
                    if (dataBuffer.length > 100) {
                        // 只保留最近的数据，优先保留可能形成标准格式的部分
                        dataBuffer = dataBuffer.substring(dataBuffer.length - 50);
                        console.log('缓冲区过长，保留最近50字符:>> ', dataBuffer);
                    }
                    
                    // 5. 检查是否有部分wn前缀
                    const wnIndex = dataBuffer.indexOf('wn');
                    if (wnIndex >= 0 && dataBuffer.length > wnIndex + 2) {
                        // 提取wn后的部分
                        const afterWn = dataBuffer.substring(wnIndex + 2);
                        const numberMatch = afterWn.match(/\d+(\.\d+)?/);
                        
                        if (numberMatch) {
                            const weightStr = numberMatch[0];
                            const weightNum = parseFloat(weightStr);
                            if (!isNaN(weightNum) && weightNum >= 0 && weightNum <= 9999.99) {
                                // 构建标准格式
                                const formattedWeight = `wn${weightStr.padStart(7, '0')}kg`;
                                console.log('✓ 从wn前缀构建标准格式:>> ', formattedWeight);
                                
                                processWeightData(weightStr);
                                
                                // 更新缓冲区
                                dataBuffer = dataBuffer.substring(wnIndex + 2 + numberMatch.index + numberMatch[0].length);
                                console.log('处理wn前缀后缓冲区:>> ', dataBuffer);
                                continue;
                            }
                        }
                    }
                }
            }catch(error){
                console.error('串口读取错误', error);
                this.weight_reader.releaseLock(); // 释放reader的锁
            } finally {
                try {
                    this.weight_reader.releaseLock(); // 释放reader的锁
                } catch (e) {
                    // 忽略已释放锁的错误
                }
            }
            
            // 处理重量数据的辅助函数
            function processWeightData(weightStr) {
                const parsedWeight = parseFloat(weightStr);
                if (!isNaN(parsedWeight) && parsedWeight >= 0 && parsedWeight <= 9999.99) {
                    self.form.weight = parsedWeight;
                    self.form.net_weight = parsedWeight;
                    console.log('✓ 成功解析的重量:>> ', parsedWeight);
                    self.total();
                    return true;
                }
                console.log('✗ 无法解析的重量:>> ', weightStr);
                return false;
            }
        },
        // 读/写米数数据
         async writeMeterData(port){
             // 确保数据缓冲区已初始化
             if (!this.dataBuffer) {
                this.dataBuffer = new Uint8Array(0);
             }
            this.meter_reader = port.readable.getReader();  //读
            this.meter_start = true;
            this.meter_write = port.writable.getWriter();  //写
            this.meterInterval = setInterval(async ()=> {
                try {
                    const data = new Uint8Array([0x55,0xAA,0x02,0x00,0x00,0x01]);
                    await this.meter_write.write(data);
                } catch (err) {
                    // 写入失败时清除定时器
                    if(this.meterInterval) {
                        clearInterval(this.meterInterval);
                        this.meterInterval = null;
                    }
                }
            }, 1000)
            try {
                while (this.meter_start) {
                    const { value, done } = await this.meter_reader.read();
                    if (done || !this.meter_start) {
                        break;
                    }
                    
                    // 将新读取的数据追加到缓冲区
                    const newBuffer = new Uint8Array(this.dataBuffer.length + value.length);
                    newBuffer.set(this.dataBuffer);
                    newBuffer.set(new Uint8Array(value), this.dataBuffer.length);
                    this.dataBuffer = newBuffer;
                    
                    // console.log('当前缓冲区长度:', this.dataBuffer.length);
                    // console.log('缓冲区数据:', this.uint8Array(this.dataBuffer));
                    
                    // 处理缓冲区中的数据帧
                    this.processDataBuffer();
                }
            } catch(error) {
                console.log('米数串口读取错误,', error);
                if (this.form.com1_status) {
                    console.log('米数串口连接断开，尝试自动重连...');
                    // 1. 重置状态
                    this.meter_start = false;
                    // 2. 确保释放资源 - 使用非异步方式清理定时器和引用
                    try {
                        // 清除定时器
                        if (this.meterInterval) {
                            clearInterval(this.meterInterval);
                            this.meterInterval = null;
                        }
                        // 先标记所有引用为null，避免循环引用
                        const reader = this.meter_reader;
                        const writer = this.meter_write;
                        const port = this.meter_port;
                        this.meter_reader = null;
                        this.meter_write = null;
                        this.meter_port = null;
                        
                        // 释放读取器（异步操作）
                        if (reader) {
                            try {
                                await reader.releaseLock();
                            } catch (e) {
                                console.log('释放读取锁错误:', e);
                            }
                        }
                        // 释放写入器（异步操作）
                        if (writer) {
                            try {
                                await writer.releaseLock();
                            } catch (e) {
                                console.log('释放写入锁错误:', e);
                            }
                        }
                        // 关闭端口（异步操作）
                        if (port) {
                            try {
                                await port.close();
                            } catch (e) {
                                console.log('关闭端口错误:', e);
                            }
                        }
                    } catch (cleanupError) {
                        console.log('清理资源时出错:', cleanupError);
                    }
                    
                    // 3. 尝试使用getPorts()自动重连（该方法不需要用户手势）
                    setTimeout(async () => {
                        try {
                            // 获取用户之前已授权的所有串口列表
                            const ports = await navigator.serial.getPorts();
                            console.log('全部ports :>> ', ports);
                            
                            if (ports && ports.length > 0) {
                                // 重置端口引用，确保从全新状态开始
                                this.meter_port = null;
                                
                                // 尝试每个可用端口
                                for (let i = 0; i < ports.length; i++) {
                                    try {
                                        this.meter_port = ports[i];
                                        console.log(`尝试连接端口 ${i+1}:`, this.meter_port);
                                        
                                        // 确保端口已关闭（使用try-catch避免未打开的端口报错）
                                        try {
                                            await this.meter_port.close();
                                            console.log('端口已关闭，准备重新打开');
                                        } catch (closeError) {
                                            console.log('关闭端口失败，可能端口未打开，继续尝试打开:', closeError);
                                        }
                                        
                                        // 重新打开端口
                                        await this.meter_port.open({ 
                                            baudRate: 19200, 
                                            flowControl: 'none', 
                                            dataBits: 8,
                                            stopBits: 1,
                                            parity: 'none'
                                        });
                                        console.log('端口打开成功，检查读写状态:', {
                                            readable: !!this.meter_port.readable,
                                            writable: !!this.meter_port.writable
                                        });
                                        
                                        // 验证可写流是否可用
                                        if (!this.meter_port.writable) {
                                            console.warn('端口打开成功但可写流不可用，尝试下一个端口');
                                            // 尝试重新初始化端口
                                            try {
                                                await this.meter_port.close();
                                                await this.meter_port.open({ 
                                                    baudRate: 19200, 
                                                    flowControl: 'none', 
                                                    dataBits: 8,
                                                    stopBits: 1,
                                                    parity: 'none'
                                                });
                                                console.log('重新初始化后端口状态:', {
                                                    readable: !!this.meter_port.readable,
                                                    writable: !!this.meter_port.writable
                                                });
                                            } catch (reinitError) {
                                                console.log('重新初始化端口失败:', reinitError);
                                            }
                                            
                                            // 如果仍然不可写，继续尝试下一个端口
                                            if (!this.meter_port.writable) {
                                                continue;
                                            }
                                        }
                                        
                                        console.log('自动重连成功，使用已授权的串口');
                                        // 重置状态并重新开始读写数据
                                        this.meter_start = true;
                                        this.writeMeterData(this.meter_port);
                                        return; // 成功连接后退出循环
                                    } catch (portError) {
                                        console.log(`连接端口 ${i+1} 失败:`, portError);
                                        // 继续尝试下一个端口
                                    }
                                }
                                
                                // 所有端口都尝试失败
                                console.log('所有可用端口连接失败');
                                throw new Error('所有已授权端口连接失败');
                            } else {
                                // 没有已授权的端口，需要用户手动触发重连
                                console.log('没有找到已授权的串口，需要用户手动授权');
                                throw new Error('未找到已授权端口');
                            }
                        } catch (reconnectError) {
                            console.log('自动重连失败:', reconnectError);
                            // 显示错误信息，让用户手动重连
                            this.$message({
                                message: `自动重连失败: ${reconnectError.message}，请点击开启按钮手动连接`,
                                type: 'error',
                                duration: 5000
                            });
                            // 设置状态让用户手动点击开启按钮
                            this.form.com1_status = false;
                        }
                    }, 3000); // 增加延迟时间到3秒，确保资源完全释放
                }
            } finally {
                // 清除定时器
                if (this.meterInterval) {
                    clearInterval(this.meterInterval);
                    this.meterInterval = null;
                }
                // 释放锁（检查是否存在，避免重复释放）
                try {
                    if (this.meter_reader) {
                        this.meter_reader.releaseLock();
                        this.meter_reader = null;
                    }
                } catch (err) {
                    console.log('释放读取锁错误', err);
                }
                
                try {
                    if (this.meter_write) {
                        this.meter_write.releaseLock();
                        this.meter_write = null;
                    }
                } catch (err) {
                    console.log('释放写入锁错误', err);
                }
                
                this.meter_start = false;
            }
        },
        hexToString2(hex) {
            var len = hex.length;
            var str = '';
            var str2 = '';
            for (var i = 0; i < len; i++) {
                str2 += hex[i];
            }
            str = parseInt(str2, 16);
            // console.log('hexToString2的 :>> ', str);
            return str
            // str = str.replace(/^0|$/g,'')
            // return str.replace(/^0|$/g,'');
        },
        uint8Array(uint8Array){
             return Array.prototype.map
            .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
            .join(',');
        },
        // 处理数据缓冲区，提取完整的数据帧
        processDataBuffer() {
            // 定义帧头模式：0x55 0xAA
            const frameHeader = [0x55, 0xAA];
            const frameLength = 12; // 完整数据帧长度
            
            // 当缓冲区数据长度足够时尝试提取帧
            while (this.dataBuffer.length >= frameLength) {
                // 查找帧头位置
                let headerIndex = -1;
                for (let i = 0; i <= this.dataBuffer.length - 2; i++) {
                    if (this.dataBuffer[i] === frameHeader[0] && this.dataBuffer[i+1] === frameHeader[1]) {
                        headerIndex = i;
                        break;
                    }
                }
                
                if (headerIndex === -1) {
                    // 没有找到帧头，清空缓冲区
                    // console.log('未找到帧头，清空缓冲区');
                    this.dataBuffer = new Uint8Array(0);
                    break;
                }
                
                // 确保从帧头开始有足够的数据
                if (this.dataBuffer.length - headerIndex >= frameLength) {
                    // 提取一个完整的帧
                    const frame = this.dataBuffer.slice(headerIndex, headerIndex + frameLength);
                    // console.log('提取到完整数据帧:', this.uint8Array(frame));
                    
                    // 处理该帧
                    this.processFrame(frame);
                    
                    // 移除已处理的数据
                    this.dataBuffer = this.dataBuffer.slice(headerIndex + frameLength);
                } else {
                    // 帧不完整，保留剩余数据
                    this.dataBuffer = this.dataBuffer.slice(headerIndex);
                    break;
                }
            }
        },
        // 处理单个完整的数据帧
        processFrame(frame) {
            // 转换为十六进制字符串数组
            const uint = this.uint8Array(frame);
            const uint_data = uint.split(',');
            
            // console.log('处理完整数据帧:', uint_data);
            
            if (uint_data.length === 12) {
                // 提取米数值
                const arr = [uint_data[5], uint_data[6], uint_data[7]];
                let final_meter = this.hexToString2(arr);
                
                // 根据数据格式调整小数位
                if (uint_data[4] === '02') {
                    final_meter = final_meter / 100;
                } else {
                    final_meter = final_meter / 10;
                }
                
                // console.log('最终米数:', final_meter);
                
                // 更新界面显示
                this.$nextTick(() => {
                    this.form.number = final_meter;
                });
                this.numberInput(final_meter);
                this.total();
            }
        },
        //编辑
        table_edit(row) {
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('edit').setData(row)
            })
        },
        //删除
        async table_del(row) {
            var reqData = { id: row.id }
            var res = await this.$API.business.inspect.execute.delete.post(reqData);
            if (res.code == 1) {
                this.$refs.table.refresh()
                this.$message.success("删除成功")
            } else {
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
        handleSuccess(data, mode) {
            if (mode == 'add') {
                this.$refs.table.refresh()
            } else if (mode == 'edit') {
                this.$refs.table.refresh()
            }
        },
        // 打印
        async table_print(row){
			var reqData = { roll_code: row.roll_code, reject_num: this.form.reject_num };
			var res = await this.$API.business.inspect.execute.print.post(reqData);
			if (res.code == 1) {
				this.$refs.printDialog.init(res.data);
			} else {
				this.$alert(res.message, "提示", { type: "error" });
			}
            setTimeout(() => {
                this.form.come = 0
                this.form.cut = 0
                this.$nextTick(() => {
                    this.$refs.comeInput.focus()
                })
            }, 500)
        },
        test_show(){
            if(!this.form.purchase_test_id) return this.$message.error('请先输入检验单号')
            let code = []
            this.houseList.map(item=>{
                code.push(item.id)
            })
            let form = {
                id: code,
                test_id: this.form.purchase_test_id,
                test_code: this.purchase_test_code,
                goods_name: this.form.goods_name,
                apply_name: this.apply_name,
                dye_factory_name: this.dye_factory_name,
                process_factory_name: this.process_factory_name,
            }
            this.dialog.print = true
            this.$nextTick(() => {
                this.$refs.printDialog.open('add').setData(form)
            })
        },
        test_show_check(){
            if(!this.form.purchase_test_id) return this.$message.error('请先输入检验单号')
            let code = []
            this.houseList.map(item=>{
                code.push(item.id)
            })
            let form = {
                id: code,
                test_id: this.form.purchase_test_id,
                test_code: this.purchase_test_code,
                goods_name: this.form.goods_name,
                apply_name: this.apply_name,
                dye_factory_name: this.dye_factory_name,
                process_factory_name: this.process_factory_name,
            }
            this.dialog.situa = true
            this.$nextTick(() => {
                this.$refs.situaDialog.open('add').setData(form)
            })
        },
        printBack(data,id,weight){
            this.form.purchase_ware_id = id
            this.purchase_ware_code = data
            this.house_weight = weight
            this.testChange(id)
        },
    }
}
</script>

<style lang="scss">
.elType{
    .el-form-item--default .el-form-item__label{
        color: #000;
        font-weight: bold;
    }
    .el-form-item__content{
        justify-content: flex-end;
    }
    .el-form-item{
        margin-bottom: 10px;
    }
    .el-radio-button__inner{
        padding: 9px
    }
}
.border{
    width: 100%;
    height: 80px;
    border: 1px solid #dcdfe6;
    padding: 5px;
}
.el-tag{
    min-height: 20px !important;
    height: 20px !important;
    line-height: 20px !important;
}
</style>
